package com.sita.cfmoto.version;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.sita.cfmoto.R;

public class UpdateDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String title = String.format(getString(R.string.newUpdateAvailable),
                getArguments().getString(Constants.APK_VERSION_NAME));
        String description = getArguments().getString(Constants.APK_UPDATE_CONTENT);
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.dialog_version_new, null);
        TextView titleView = (TextView) view.findViewById(R.id.title);
        TextView descriptionView = (TextView) view.findViewById(R.id.description);
        titleView.setText(title);
        descriptionView.setText(description);

        TextView laterBtn = (TextView) view.findViewById(R.id.btn_later);
        TextView nowBtn = (TextView) view.findViewById(R.id.btn_now);

        final NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        laterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationManager.cancel(Constants.UPDATE_NOTIFICATION_ID);
                dismiss();
            }
        });
        nowBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationManager.cancel(Constants.UPDATE_NOTIFICATION_ID);
                gotoMarket();
                dismiss();
            }
        });

        // Use the Builder class for convenient dialog construction

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        // Create the AlertDialog object and return it
        return builder.create();
    }


    private void goToDownload() {
        Intent intent = new Intent(getActivity().getApplicationContext(), DownloadService.class);
        intent.putExtra(Constants.APK_DOWNLOAD_URL, getArguments().getString(Constants.APK_DOWNLOAD_URL));
        getActivity().startService(intent);
    }

    private void gotoMarket() {
        String url = getArguments().getString(Constants.APK_DOWNLOAD_URL);
        Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        getActivity().startActivity(urlIntent);
    }
}
